package com.wjw.controller;

import com.wjw.enums.OrderStatusEnum;
import com.wjw.enums.PayMethod;
import com.wjw.pojo.OrderStatus;
import com.wjw.pojo.UserAddress;
import com.wjw.pojo.bo.AddressBO;
import com.wjw.pojo.bo.SubmitOrderBO;
import com.wjw.pojo.vo.MerchantOrdersVO;
import com.wjw.pojo.vo.OrderVO;
import com.wjw.service.AddressService;
import com.wjw.service.OrderService;
import com.wjw.utils.CookieUtils;
import com.wjw.utils.MobileEmailUtils;
import com.wjw.utils.WJWJSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/12/20 16:29
 * 4
 */
@RestController
@Api(value = "订单相关", tags = {"订单相关的api接口"})
@RequestMapping("orders")
public class OrdersController extends BaseController{

    @Autowired
    private OrderService orderService;

    @Autowired
    private RestTemplate restTemplate;

    @ApiOperation(value = "根据用户id查询收获地址列表", notes = "根据用户id查询收获地址列表", httpMethod = "POST")
    @PostMapping("/create")
    public WJWJSONResult create(@RequestBody SubmitOrderBO submitOrderBO, HttpServletRequest request, HttpServletResponse response){

        if (submitOrderBO.getPayMethod() != PayMethod.WEIXIN.type && submitOrderBO.getPayMethod() != PayMethod.ALIPAY.type) {
            return WJWJSONResult.errorMsg("支付方式不支持");
        }

//        System.out.println(submitOrderBO.toString());

        // 1. 创建订单
        OrderVO orderVO = orderService.createOrder(submitOrderBO);
        String orderId = orderVO.getOrderId();

        // 2. 创建订单后，移除购物车中已结算（已提交）的商品
        // TODO 整合redis之后，完善购物车中的已结算商品清除，并且同步到前端的cookie
//        CookieUtils.setCookie(request, response, FOODIE_SHOPCART, "", true);



        // 3. 向支付中心发送当前订单，用于保存支付中心的订单数据
        MerchantOrdersVO merchantOrdersVO = orderVO.getMerchantOrdersVO();
        merchantOrdersVO.setReturnUrl(payReturnUrl);

        /**
         * 为了方便测试购买操作，所有价格都设为0.01
         */
        merchantOrdersVO.setAmount(1);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("imoocUserId", "imooc");
        headers.add("password", "imooc");

        HttpEntity<MerchantOrdersVO> entity = new HttpEntity<>(merchantOrdersVO, headers);
        // 第二个参数：请求request  第三个参数：返回值类型
        ResponseEntity<WJWJSONResult> responseEntity = restTemplate.postForEntity(paymentUrl, entity, WJWJSONResult.class);

        WJWJSONResult paymentResult = responseEntity.getBody();
        if (paymentResult.getStatus() != 200) {
            return WJWJSONResult.errorMsg("支付中心订单创建失败，请联系管理员");
        }

        /*
        为了测试方便，选择支付宝方式时，直接写成支付成功
         */
        if (submitOrderBO.getPayMethod() == PayMethod.ALIPAY.type){
            orderService.updateOrderStatus(orderId, OrderStatusEnum.WAIT_DELIVER.type);
        }

        return WJWJSONResult.ok(orderId);
    }

    /**
     * 支付成功的回调
     * @param merchantOrderId 订单id
     * @return
     */
    @PostMapping("/notifyMerchantOrderPaid")
    public Integer notifyMerchantOrderPaid(String merchantOrderId) {
        orderService.updateOrderStatus(merchantOrderId, OrderStatusEnum.WAIT_DELIVER.type);
        return HttpStatus.OK.value();
    }

    /**
     * 查询订单状态（是否支付成功）
     * @param orderId
     * @return
     */
    @PostMapping("/getPaidOrderInfo")
    public WJWJSONResult getPaidOrderInfo(String orderId) {
        OrderStatus orderStatus = orderService.queryOrderStatusInfo(orderId);
        return WJWJSONResult.ok(orderStatus);
    }

}
